//相关业务逻辑
$(function(){
	scan.setConfig();
	scan.getValue();
	page.bind();
	$(".deviceDiv").hide();
});


var page={//页面总变量
		bind:function(){
			$("#orderId").bind("change",function(){
//				var orderId=$("#orderId").val();
//				page.getOrderDetail(orderId);
//				page.getWorkshopName();
				page.idChange();
			});
			
			$("#deviceDivShow").bind("click",function(){
				var text=$(this).text();
				if(text=='收起'){
					$(".deviceDiv").hide("slow");
					$(this).text("填写设备信息");
				}else{
					$(".deviceDiv").show("slow");
					$(this).text("收起");
				}
			});
			
			$("#addProBtn").bind("click",function(){
				$("#addProTr").show("slow");
			});
			
			$("#inWorkShop").bind("change",function(){
				var inWorkshop=$("#inWorkShop option:selected").val();
				window.localStorage.setItem('inWorkShop',inWorkshop);
			});
			
			$("#addFactoryBtn").bind("click",function(){
				$("#factoryNameTr").show("slow");
			});
			
			$("#addDeviceIdBtn").bind("click",function(){
				$("#deviceIdTr").show("slow");
			});
			
			$("#addDeviceNameBtn").bind("click",function(){
				$("#deviceNameTr").show("slow");
			});
			
			$("#addFactoryNameBtn").bind("click",function(){
				var addFactoryName=$("#addFactoryName").val();
				if(addFactoryName==''){
					layAlert("请输入厂家");
					return false;
				}
				$("#factoryNameTr").hide("slow");
				$("#factoryName").append("<option value='"+addFactoryName+"'>"+addFactoryName+"</option>");
				$("#factoryName option[value='"+addFactoryName+"']").attr("selected", "selected");
			});
			
			
			$("#addDeviceBtn").bind("click",function(){
				var addDeviceId=$("#addDeviceId").val();
				if(addDeviceId==''){
					layAlert("请输入设备编号");
					return false;
				}
				$("#deviceIdTr").hide("slow");
				$("#deviceId").append("<option value='"+addDeviceId+"'>"+addDeviceId+"</option>");
				$("#deviceId option[value='"+addDeviceId+"']").attr("selected", "selected");
			});
			
			$("#addDeviceNBtn").bind("click",function(){
				var addDeviceName=$("#addDeviceName").val();
				if(addDeviceName==''){
					layAlert("请输入设备名称");
					return false;
				}
				$("#deviceNameTr").hide("slow");
				$("#deviceName").append("<option value='"+addDeviceName+"'>"+addDeviceName+"</option>");
				$("#deviceName option[value='"+addDeviceName+"']").attr("selected", "selected");
			});
			
			$("#addProTime").bind("keyup",function(){
				   var re=/^[1-9]+[0-9]*]*$/;
				   var addProTime=$("#addProTime").val();
				   if(!re.test(addProTime)){
					   addProTime=addProTime.substring(0,addProTime.length-1);
					   $("#addProTime").val(addProTime);
					   return false;
				   }
			   });
			
			$("#addProcedureBtn").bind("click",function(){
				var workshop=$("#workshopName option:selected").val();
				var procedure=$("#addProName").val();
				var useTime=$("#addProTime").val();
				var creatUser=$("#userName").text();
				
				if(workshop==''){
					layAlert("请选择车间");
					return false;
				}
				if(procedure==''){
					layAlert("请填写工序名称");
					return false;
				}
				if(addProTime==''){
					layAlert("请填写工序作业时间");
					return false;
				}
				if(creatUser==''){
					layAlert("未获取到创建人信息");
					return false;
				}
				var adddata={
						'workshop':$("#workshopName option:selected").val(),
						'procedure':$("#addProName").val(),
						'useTime':$("#addProTime").val(),
						'creatUser':$("#userName").text()
				}
				ajaxUtil.ajaxRuquest("weiXin/addProcedur",adddata,function(data){
					layer.msg(data, {icon: 1});
					$("#addProTr").hide("slow");
					var procedure=$("#addProName").val();
					$("#workingProcedureName").append("<option value='"+procedure+"'>"+procedure+"</option>");
					$("#workingProcedureName option[value='"+procedure+"']").attr("selected", "selected");
					$("#addProName").val("");
					$("#addProTime").val("");
				});
			});

			//选中车间时调用获取工序方法
			$("#workshopName").bind("change",function(){
				var workshopName=$("#workshopName option:selected").val();//获取选中的下拉框的值
				window.localStorage.setItem('workshopName',workshopName);
				$("#noReason").html("");
				page.getWorkingProcedureName(workshopName);
				var sendData={
					'workShopName':	$("#workshopName option:selected").val()
				}
				page.getFactory(sendData);
				page.getDeviceId(sendData);
				page.getDeviceName(sendData);
			});
			
		   $("#machining").bind("change",function(){
			  var orderId=$("#orderId").val();//获取选中的下拉框的值
			  if(""==orderId){
				  layAlert("请先扫码输入订单编号");
				  return false;
		 	  }
			  var machining=$("#machining option:selected").val();
			  if(''==machining){
				  layAlert("请选择加工对象");
				  return false;
			  }
			  page.getColor(orderId,machining);
		   });
		   
		    $("#workingProcedureName").bind("change",function(){
		    	var workshopName=$("#workshopName option:selected").val();
		    	var workingProcedureName=$("#workingProcedureName option:selected").val();
		    	window.localStorage.setItem('workingProcedureName',workingProcedureName);
		    	if(workingProcedureName=='交接出库'){
					$(".inWorkShop").show("slow");
				}else{
					$(".inWorkShop").hide("slow");
					$("#inWorkShop option[value='']").attr("selected", "selected");
				}
		    	page.getNoReason(workshopName,workingProcedureName);
		    });
		   
		   $("#reportBtn").bind("click",function(){
			   var sendData=page.insertParam();
			   if(!sendData){
				   return false;
			   }
			   ajaxUtil.ajaxRuquest('weiXin/insertReport',sendData,function(data){
					layAlert(data);
					$(".kuangHeGe").val(0);
					$(".kuangNoHeGe").val(0);
					$(".tuiHeGe").val(0);
					$(".tuiNoHeGe").val(0);
					$(".jinShuQuanHeGe").val(0);
					$(".jinShuQuanNoHeGe").val(0);
					$(".jinShuTuiHeGe").val(0);
					$(".jinShuTuiNoHeGe").val(0);
			   });
		   });
		},
		colorBind:function(len){
			for(var i=0;i<len;i++){
				$("."+i).bind("keyup",function(){
					var className=$(this).prop("class");
					var numClass=className.substring(className.length-1,className.length);
					var re=/^[0-9]*]*$/;
					var qualified=$(this).val();
					if(!re.test(qualified)){
					   qualified=qualified.substring(0,qualified.length-1);
					}
					if($('.'+numClass).index(this)<=0){
						$("."+numClass).val(qualified);
					}else{
						$(this).val(qualified);
					}
				})
			}
		},
		getOrderDetail:function(orderId){
			$.ajax({
				url:'weiXin/getOrderDetail',
				data:{
					'orderId':orderId
				},
				success:function(data){
					if(data.result){
						data=data.data;
						$("#orderCount").val(data[0].orderCount);
					}else{
						layAlert(data.info);
						$("#orderCount").val("");
					}
				}
			});
		},
		getWorkshopName:function(){
			var orderId=$("#orderId").val();
			ajaxUtil.ajaxRuquest('orderProcedureTemplate/getReportWorkShop',{"orderId":orderId},function(data){
				var html="<option value=''>全部</option>";
				if(data.length>0){
					for(var i=0;i<data.length;i++){
						html=html+"<option value='"+data[i].id+"'>"+data[i].workshopName+"</option>";
					}
				}else{
					html=html+"<option value=''>您还没有设置报工车间</option>";
				}
				$("#workshopName").append(html);
				$("#inWorkShop").append(html);
				var workshopName=$("#workshopName option:selected").val();
//				//进入页面查询所有工序
				var sendData={
						'workShopName':	$("#workshopName option:selected").val()
				}
				page.selectedWork();
				page.getFactory(sendData);
				page.getDeviceId(sendData);
				page.getDeviceName(sendData);
			});
		},
		//根据车间名称获取工序名称
		getWorkingProcedureName:function(workshopName){
			var orderId=$("#orderId").val();
			ajaxUtil.ajaxRuquest('orderProcedureTemplate/getReportProcedure',{'workShopId':workshopName,"orderId":orderId},function(data){
				var html="<option value=''>全部</option>";
				if(data.length>0){
					for(var i=0;i<data.length;i++){
						html=html+"<option value='"+data[i].id+"'>"+data[i].processName+"</option>";
					}
				}else{
					html=html+"<option value=''>该车间没有您的报工工序</option>";
				}
				$("#workingProcedureName").html("");
				$("#workingProcedureName").append(html);
				var workingProcedureName=window.localStorage.getItem('workingProcedureName');
				if(workingProcedureName!=''){
					$("#workingProcedureName option[value='"+workingProcedureName+"']").attr("selected", "selected");
				    if(workingProcedureName=='交接出库'){
				    	$(".inWorkShop").show("slow");
				    }
				}
			});
		},
		getColor:function(orderId,machining){
			ajaxUtil.ajaxRuquest('weiXin/getColor',{'orderId':orderId},function(data){
				var html="";
				if(machining=='整架'){
					for(var i=0;i<data.length;i++){
						var className='one';
						var chackHtml="<input type='checkbox' name='colorCheck' value='"+data[i].rowIndex+"' />";
						if(i%2==0){
							className='two';
						}
						if(data[i].quanColor!='无'){
							html+="<tr class="+className+"><td colspan='2'  style='text-align:center'>"+chackHtml+
							"<span class='kaungColor'>"+data[i].quanColor+"</span>(板材框)</td>"+
							"<td colspan='2'><input type='text' class='input-text kuangHeGe "+i+"' placeholder='合格' value='0' /></td>"+
							"<td colspan='2'><input type='text' class='input-text kuangNoHeGe' placeholder='不合格' value='0' /></td>"+
							"</tr>";
							chackHtml="";
						}
						if(data[i].tuiColor!='无'){
							html+="<tr class="+className+"><td colspan='2'  style='text-align:center'>"+chackHtml+
							"<span class='tuiColor'>"+data[i].tuiColor+"</span>(板材腿)</td>"+
							"<td colspan='2'><input type='text' class='input-text tuiHeGe "+i+"' placeholder='合格' value='0' /></td>"+
							"<td colspan='2'><input type='text' class='input-text tuiNoHeGe' placeholder='不合格' value='0' /></td>"+
							"</tr>";
							chackHtml="";
						}
						if(data[i].jinShuQuanColor!='无'){
							html+="<tr class="+className+"><td colspan='2'  style='text-align:center'>"+chackHtml+
							"<span class='jinShuQuanColor'>"+data[i].jinShuQuanColor+"</span>(金属框)</td>"+
							"<td colspan='2'><input type='text' class='input-text jinShuQuanHeGe "+i+"' placeholder='合格'  value='0'/></td>"+
							"<td colspan='2'><input type='text' class='input-text jinShuQuanNoHeGe' placeholder='不合格' value='0' /></td>"+
							"</tr>";
							chackHtml="";
						}
						if(data[i].jinShuTuiColor!='无'){
							html+="<tr class="+className+"><td colspan='2'  style='text-align:center'>"+chackHtml+
							"<span class='jinShuTuiColor'>"+data[i].jinShuTuiColor+"</span>(金属腿)</td>"+
							"<td colspan='2'><input type='text' class='input-text jinShuTuiHeGe "+i+"' placeholder='合格' value='0' /></td>"+
							"<td colspan='2'><input type='text' class='input-text jinShuTuiNoHeGe' placeholder='不合格' value='0' /></td>"+
							"</tr>";
							chackHtml="";
						}
					}
				}else {
					html+="<tr><td colspan='6'  style='text-align:center'>"+machining+"</td></tr>";
					for(var i=0;i<data.length;i++){
						var clor=data[i].quanColor;
						if(machining=='腿'){
							clor=data[i].tuiColor;
						}
						if(machining=='金属框'){
							clor=data[i].jinShuQuanColor;
						}
						if(machining=='金属腿'){
							clor=data[i].jinShuTuiColor;
						}
						html+="<tr><td colspan='2'><input type='checkbox' name='colorCheck' value='"+data[i].rowIndex+"' />" +
						"<span class='kaungColor'>"+clor+"</span></td>"+
						"<td colspan='2'><input type='text' class='input-text kuangHeGe' placeholder='合格'  /></td>"+
                        "<td colspan='2'><input type='text' class='input-text kuangNoHeGe' placeholder='不合格' value='0' /></td></tr>";
					}
				}
				$("#color").html(html);
				page.colorBind(data.length);
			});
		},
		idChange:function(){
			var orderId=$("#orderId").val();
			page.getOrderDetail(orderId);
			page.getWorkshopName();
			page.getOrderMeType(orderId);
			var machining=$("#machining option:selected").val();
			if(''==machining){
				return false;
			}
			page.getColor(orderId,machining);
		},
		getNoReason:function(workShopName,produce){
			ajaxUtil.ajaxRuquest('weiXin/getNoReason',{'workShopName':workShopName,'produce':produce},function(data){
				var html="<td colspan='2'></td><td colspan='4'>";
				for(var i=0;i<data.length;i++){
					if(data[i]!=''&&data[i]!=null){
						html+="<input type='checkbox' name='noHeGe' value='"+data[i]+"'>"+data[i];
					}
				}
				html+="</td>";
				if(data.length<=0){
					html="";
				}
				$("#noReason").html(html);
				page.checkBoxBind();
			});
		},
		checkBoxBind:function(){
			$("[name = noHeGe]:checkbox").bind("click",function(){
				var xx=$(this).val();
				var yy=$("#noQualifiedReason").val();
				if(yy.indexOf(xx) > 0){
					yy=yy.replace(xx,"")
					$("#noQualifiedReason").val(yy);
				}else{
					$("#noQualifiedReason").val(yy+" "+xx);
				}
			});
		},
//		insertProcedure:function(adddata){
//			ajaxUtil.ajaxRuquest('weiXin/addProcedur',adddata,function(data){
//				layer.msg(data,{icon:1});
//			});
//		},
//		getTouLiao:function(){
//			var sendData={
//					'color':$("#color option:selected").val(),
//					'orderId':$("#orderId").val(),
//					'machining':$("#machining option:selected").val()
//			}
//			ajaxUtil.ajaxRuquest("weiXin/getOrderFieeding",sendData,function(data){
//				$("#felldCouont").text("投料数："+data);
//			});
//		},
		getFactory:function(sendData){
			ajaxUtil.ajaxRuquest("weiXin/getFactory",sendData,function(data){
				var html="<option value=''>请选择</option>"
			    for(var i=0;i<data.length;i++){
			    	html+="<option value='"+data[i]+"'>"+data[i]+"</option>";
			    }
				$("#factoryName").html("");
				$("#factoryName").append(html);
			});
		},
		getDeviceId:function(sendData){
			ajaxUtil.ajaxRuquest("weiXin/getDeviceId",sendData,function(data){
				var html="<option value=''>请选择</option>"
				for(var i=0;i<data.length;i++){
			    	html+="<option value='"+data[i]+"'>"+data[i]+"</option>";
			    }
				$("#deviceId").html("");
				$("#deviceId").append(html);
			});
		},
		getDeviceName:function(sendData){
			ajaxUtil.ajaxRuquest("weiXin/getDeviceName",sendData,function(data){
				var html="<option value=''>请选择</option>"
				for(var i=0;i<data.length;i++){
			    	html+="<option value='"+data[i]+"'>"+data[i]+"</option>";
			    }
				$("#deviceName").html("");
				$("#deviceName").append(html);
			});
		},
		insertParam:function(){
		   var machining=$("#machining option:selected").val();
		   var touchPeople=$("#userName").text();
		   var orderId=$("#orderId").val();
		   var touchTime=$("#touchTime").val();
		   var workshopName=$("#workshopName option:selected").val();
		   var procedur=$("#workingProcedureName option:selected").val();
		   var noQualifiedReason=$("#noQualifiedReason").val();
		   var factoryName=$("#factoryName option:selected").val();
		   var deviceId=$("#deviceId option:selected").val();
		   var deviceName=$("#deviceName option:selected").val();
		   var inWorkShop=$("#inWorkShop option:selected").val();
		   if(machining==''){
				layAlert("请选择加工对象");
				return false;
			}
		   if(''==workshopName){
			   layAlert("请先选择车间");
			   return false;
		   }
		   if(orderId==''){
			   layAlert("请先扫描二维码扫描订单编号");
			   return false;
		   }
		   if(procedur==""){
			   layAlert("请选择工序");
			   return false;
		   }
		   if(procedur=="交接出库" && inWorkShop==""){
				   layAlert("请选择接收车间");
				   return false;
		   }
		   if(workshopName==inWorkShop){
			   layAlert("出入库车间不能相同");
			   return false;
		   }
		   var rowIndex=new Array();  
			$('input[name="colorCheck"]:checked').each(function(){  
				rowIndex.push($(this).val());//向数组中添加元素  
			}); 
			if(rowIndex.length<=0){
				layAlert("请勾选报工颜色");
				return false;
			}
			
			var data=new Object();
			var sendData=new Array();
			data.touchPeople=touchPeople;
			data.orderId=orderId;
			data.time=touchTime;
			data.workShopName=workshopName;
			data.procedur=procedur;
			data.machining=machining;
			data.factoryName=factoryName;
			data.deviceId=deviceId;
			data.deviceName=deviceName;
			data.inWorkShop=inWorkShop;
			
			//板材框
		   var kaungColor=arrayUtil.getClassArrayText("kaungColor");
		   var kuangHege=arrayUtil.getClassArrayVal("kuangHeGe");
		   var kuangNoHeGe=arrayUtil.getClassArrayVal("kuangNoHeGe");
		   
		   //板材腿
		   var tuiColor=arrayUtil.getClassArrayText("tuiColor");
		   var tuiHeGe=arrayUtil.getClassArrayVal("tuiHeGe");
		   var tuiNoHeGe=arrayUtil.getClassArrayVal("tuiNoHeGe");
		   
		   //金属框
		   var jinShuQuanColor=arrayUtil.getClassArrayText("jinShuQuanColor");
		   var jinShuQuanHeGe=arrayUtil.getClassArrayVal("jinShuQuanHeGe");
		   var jinShuQuanNoHeGe=arrayUtil.getClassArrayVal("jinShuQuanNoHeGe");
		   
           //金属腿
		   var jinShuTuiColor=arrayUtil.getClassArrayText("jinShuTuiColor");
		   var jinShuTuiHeGe=arrayUtil.getClassArrayVal("jinShuTuiHeGe");
		   var jinShuTuiNoHeGe=arrayUtil.getClassArrayVal("jinShuTuiNoHeGe");
		   
		
		   for(var i=0;i<rowIndex.length;i++){
			   var roIndex=rowIndex[i];
			   data.rowIndex=roIndex;
			   var index=rowIndex[i]-1;
			   var dataCopy2=jQuery.extend({}, data);
			   if(machining=="整架"){
				   dataCopy2.machining="框";
				   if(tuiColor.length>0){
					   var dataCopy=jQuery.extend({}, data);
					   dataCopy.color=tuiColor[index];
					   dataCopy.qualified=tuiHeGe[index];
					   dataCopy.noQualified=tuiNoHeGe[index];
					   dataCopy.machining="腿";
					   sendData.push(dataCopy);
				   }
				   if(jinShuQuanColor.length>0){
					   var dataCopy3=jQuery.extend({}, data);
					   dataCopy3.color=jinShuQuanColor[index];
					   dataCopy3.qualified=jinShuQuanHeGe[index];
					   dataCopy3.noQualified=jinShuQuanNoHeGe[index];
					   dataCopy3.machining="金属框";
					   sendData.push(dataCopy3);
				   }
				   if(jinShuTuiColor.length>0){
					   var dataCopy4=jQuery.extend({}, data);
					   dataCopy4.color=jinShuTuiColor[index];
					   dataCopy4.qualified=jinShuTuiHeGe[index];
					   dataCopy4.noQualified=jinShuTuiNoHeGe[index];
					   dataCopy4.machining="金属腿";
					   sendData.push(dataCopy4);
				   }
			   }
			   dataCopy2.color=kaungColor[index];
			   dataCopy2.qualified=kuangHege[index];
			   dataCopy2.noQualified=kuangNoHeGe[index];
			   sendData.push(dataCopy2);
		   }
		   for(var i=0;i<sendData.length;i++){
			   if(sendData[i].qualified==''){
				   layAlert("请填写合格数");
				   return false;
			   }
			   if(sendData[i].noQualified==''){
				   layAlert("请填写不合格数");
				   return false;
			   }
			   if(sendData[i].color=='无'){
				   layAlert("请先设置颜色");
				   return false;
			   }
		   }
		   console.log(sendData);
		   return {'reportArrayJSONStr':JSON.stringify(sendData)} ;
		},
		selectedWork:function(){
			var workshopName=window.localStorage.getItem('workshopName');
			var inWorkShop=window.localStorage.getItem('inWorkShop');
			page.getWorkingProcedureName(workshopName);
			if(workshopName!=null){
				$("#workshopName option[value='"+workshopName+"']").attr("selected", "selected");
				$("#inWorkShop option[value='"+inWorkShop+"']").attr("selected", "selected");
			}
		},
		//获取物料类型（修改明细表之后增加）
		getOrderMeType:function(orderId){
			ajaxUtil.ajaxRuquest("weiXin/getOrderMeType",{"orderId":orderId},function(data){
				var html="<option value='整架'>整架</option>"
				for(var i=0;i<data.length;i++){
			    	html+="<option value='"+data[i]+"'>"+data[i]+"</option>";
			    }
				$("#machining").html("");
				$("#machining").append(html);
			});
		}
}

var scan={
		setConfig:function(){
			var userName=$("#userName").text();
			$.ajax({
				url:'weiXin/getConfig', 
				data:{
					'userName':userName
				},
	            success:function(data){
	            	wx.config({
	            		beta: true,// 必须这么写，否则在微信插件有些jsapi会有问题
	 				    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
	 				    appId: data.appId,
	 		            // 必填，生成签名的时间戳
	 		            timestamp:""+data.timestamp,
	 		            // 必填，生成签名的随机串
	 		            nonceStr:data.nonceStr,
	 		            // 必填，签名，见附录1
	 		            signature:data.signature,
	 		            // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
	 		            jsApiList : [ 'checkJsApi', 'scanQRCode' ]
	            	});
	            }
			});
		},
		getValue:function(){
			$("#scanQRCode").click(function() {
	            wx.scanQRCode({
	                // 默认为0，扫描结果由微信处理，1则直接返回扫描结果
	                needResult : 1,
	                desc : 'scanQRCode desc',
	                success : function(res) {
	                    //扫码后获取结果参数赋值给Input
	                    var url = res.resultStr;
	                    //商品条形码，取","后面的
	                    if(url.indexOf(",")>=0){
	                        var tempArray = url.split(',');
	                        var tempNum = tempArray[1];
	                        $("#orderId").val(tempNum);
	                    }else{
	                        $("#orderId").val(url);
	                    }
	                    page.idChange();
	                },
	               error: function(res) {
	                if (res.errMsg.indexOf('function_not_exist') > 0) {
	                    alert('版本过低请升级');
	                }
	            }
	            });
	        });
		}
}

//{
//'touchPeople':touchPeople,
//'orderId':orderId,
//'time':touchTime,
//'workShopName':workshopName,
//'procedur':procedur,
//'machining':machining,
//'color':color,
//'qualified':qualified,
//'noQualified':noQualified,
//'noQualifiedReason':noQualifiedReason,
//'factoryName':factoryName,
//'deviceId':deviceId,
//'deviceName':deviceName,
//'inWorkShop':inWorkShop
//}


